package com.whjfxx.terminal.commons;

import com.whjfxx.terminal.exceptions.BizException;
import org.apache.commons.codec.binary.Base64;

import java.io.UnsupportedEncodingException;

/**
 * Created by b.c on 2022/6/20 17:59
 */
public class Base64Util {

    public static byte[] stringToBase64(String key) {
        return Base64.decodeBase64(key.getBytes());
    }

    /**
     * Base64装换成字符串
     */
    public static String base64ToString(byte[] key) {
        return new Base64().encodeToString(key);
    }

    /**
     * Base64装换成字符串
     */
    public static String encodeToString(String key) {
        try {
            byte[] bytes = key.getBytes("utf-8");
            return new Base64().encodeToString(bytes);
        } catch (UnsupportedEncodingException e) {
            throw BizException.build("数据转码失败1");
        }
    }

    /**
     * Base64装换成字符串
     */
    public static String decodeToString(String key) {
        try {
            byte[] bytes = key.getBytes("utf-8");
            byte[] decodeBytes = Base64.decodeBase64(bytes);
            return new String(decodeBytes, "utf-8");
        } catch (UnsupportedEncodingException e) {
            throw BizException.build("数据转码失败2");
        }
    }

    public static void main(String[] args) {
        String a = "{\n" +
                "\"app_name\":\"宜昌医保\",\n" +
                "\"func_name\":\"读卡库\",\n" +
                "\"app_ver\":\"1.0\",\n" +
                "\"version\":\"100\",\n" +
                "\"terminal_sn\":\"SN123120320130120331\",\n" +
                "\"terminal_type\":\"联迪 A8\",\n" +
                "\"terminal_local\":{\"lon\":114.24921,\"lat\":30.57733},\n" +
                "\"terminal_address\":\"\",\n" +
                "\"merchant_id\":\"\",\n" +
                "\"terminal_id\":\"\",\n" +
                "\"req_time\":\"20220503121201\",\n" +
                "\"key_sign\":\"782045FFE74E40C4009320D4639AD52\"\n" +
                "}";

        String encode = encodeToString(a);
        System.out.println(encode);
        String decode = decodeToString(encode);
        System.out.println(decode);

        String b = "eyJhcHBfbmFtZSI6IuWunOaYjOWMu+S/nSIsImF1dGhfZW5kIjoiMjAyMzA1MDMxMjEyMDEiLCJhdXRoX2V4cCI6IjEyIiwiYXV0aF9leHBfdHlwZSI6Ik4iLCJjaGVja19jeWNsZSI6ImQiLCJmdW5jX25hbWUiOiLor7vljaHlupMiLCJrZXlfc2lnbiI6IjIyMkQ0NTMyMzA0RUM0QzRDMDQxODQ0RUI4QjFEQzRBIiwidGVybWluYWxfc24iOiIxOTJDQUM3MzgyMzQiLCJ0ZXJtaW5hbF90eXBlIjoi6IGU6L+qIEE4In0=";
        System.out.println(decodeToString(b));

    }
}
